package com.vq3.digitalizationsoftwareintegrates.Utils.PermissionControl;

import com.vq3.digitalizationsoftwareintegrates.Utils.ExceptionHandler.MyAuthenticationFailureHandler;
import com.vq3.digitalizationsoftwareintegrates.Utils.ExceptionHandler.MyAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**权限控制中心
 *
 * */

@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    UserDetailsService userDetailsService;
    @Resource
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Resource
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Resource
    private VerifyCodeFilter verifyCodeFilter;


    // 指定密码的加密方式    @Bean    public PasswordEncoder passwordEncoder() {//        return new BCryptPasswordEncoder();        return new PasswordEncoder() {            @Override            public String encode(CharSequence charSequence) {                return charSequence.toString();            }            @Override            public boolean matches(CharSequence charSequence, String s) {                return Objects.equals(charSequence.toString(), s);            }        };    }
// 配置用户及其对应的角色

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    // 配置 URL 访问权限
    @Override
    protected  void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() // 开启 HttpSecurity 配置
                .and().formLogin()
                .loginPage("/login.html")//登录的页面
                .loginProcessingUrl("/login").permitAll()//登录表单提交的页面
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/index.html",true)
                /**登录成功处理器/失败处理器
                 * */
                .successHandler(myAuthenticationSuccessHandler)
                .failureHandler(myAuthenticationFailureHandler)
                .and().authorizeRequests()

                /**权限控制中心，慎重修改！
                 *
                 * */
                .antMatchers("/admin/**").hasRole("ADMIN") // admin/** 模式URL必须具备ADMIN角色
                .antMatchers("/user/**").permitAll() // 该模式需要ADMIN或USER角色
                .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // 需ADMIN和DBA角色
                .antMatchers("/login.html").permitAll()// login界面全部授权
                .antMatchers("/CC/**").permitAll()//对验证码授权
                .antMatchers("/static/Css/**").permitAll()//对css放行
                .antMatchers("/static/Js/**").permitAll()//对js放行
                .antMatchers("/static/Img/**").permitAll()//对图片放行
                .antMatchers("/static/**").permitAll()//对图片放行
                .antMatchers("/register/**").permitAll()//对注册页面放行
                .antMatchers("/index.html").hasAuthority("p1")//首页条件放行
                .antMatchers("/templates/Spot_Check/Spot_Check_Add_Background.html").hasAnyAuthority("s2","sp1")


                .anyRequest().authenticated() // 用户访问其它URL都必须认证后访问（登录后访问）

                .and().csrf().disable(); // 关闭csrf
        /**先执行验证码的验证*/
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);



    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}